//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer
{

    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;
    private loginView: LoginView;
    private _resourceLoadComplete: boolean;
    private _socketConnectComplete: boolean;
    private _isCreateScene: boolean;

    public constructor()
    {
        document.title = "BUG帝国";
        super();
        this._resourceLoadComplete = false;
        this._socketConnectComplete = false;
        this._isCreateScene = false;
        Players.getInstance().isLogin = false;
        this.addEventListener( egret.Event.ADDED_TO_STAGE, this.onAddToStage, this );
    }

    private onAddToStage( event: egret.Event )
    {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild( this.loadingView );

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener( RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this );
        RES.loadConfig( "resource/resource.json", "resource/" );
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete( event: RES.ResourceEvent ): void
    {
        RES.removeEventListener( RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this );
        RES.addEventListener( RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this );
        RES.addEventListener( RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this );
        RES.addEventListener( RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this );

        RES.loadGroup( "login" );
        this.loadingView.setProgress( 0, 2 );
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete( event: RES.ResourceEvent ): void
    {
        if ( event.groupName == "preload" )
        {
            this._resourceLoadComplete = true;
            this.stage.removeChild( this.loadingView );

            RES.removeEventListener( RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this );
            RES.removeEventListener( RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this );
            RES.removeEventListener( RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this );
            this.createGameScene();
        }

        if ( event.groupName == "login" )
        {
            RES.loadGroup( "preload" );
            this.loadingView.setProgress( 0, 2 );
            GameBus.getInstance().addEventListener( SocketEvent.CONNECT, this.socketCreated, this );
            Socket.getInstance().addSocket();

            GameBus.getInstance().addEventListener( LoginEvent.CheckLogin, this.checkLogin, this );
            this.loginView = new LoginView();
            this.stage.addChild( this.loginView );
        }
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError( event: RES.ResourceEvent ): void
    {
        //TODO
        console.warn( "Group:" + event.groupName + " has failed to load" );
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete( event );
    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress( event: RES.ResourceEvent ): void
    {
        if ( event.groupName == "preload" )
        {
            this.loadingView.setTextPos( 300 );
            this.loadingView.setProgress( event.itemsLoaded, event.itemsTotal );
        }
        if ( event.groupName == "login" )
        {
            this.loadingView.setTextPos( 700 );
            this.loadingView.setProgress( event.itemsLoaded, event.itemsTotal );
        }
    }

    private socketCreated( event: SocketEvent ): void
    {
        this._socketConnectComplete = true;
        GameBus.getInstance().removeEventListener( SocketEvent.CONNECT, this.socketCreated, this );

        this.createGameScene();
    }

    private textfield: egret.TextField;

    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene(): void
    {
        if ( this._resourceLoadComplete == false || Players.getInstance().isLogin == false || this._isCreateScene || this._socketConnectComplete == false )
            return;

        this.register();
        this._isCreateScene = true;
        var stage: GameStage = new GameStage();
        this.addChild( stage );
        GameBus.getInstance().dispatchEvent( new GameEvent( GameEvent.GameStart ) );
    }

    /**注册器**/
    private register(): void
    {
        Players.getInstance();
        Fights.getInstance();
    }
    
    /**检查登录**/
    private checkLogin( event: LoginEvent ): void
    {
        GameBus.getInstance().removeEventListener( LoginEvent.CheckLogin, this.checkLogin, this );
        //data   {loginType:null,result:-1,status:-1,token:null}
        if ( event.data && event.data.status != -1 )
        {
            //已经登录了
            Players.getInstance().isLogin = true;
            Players.getInstance().rid = event.data.token;
            this.loginView.dispose();
            this.stage.removeChild( this.loginView );
            this.createGameScene();
        }
        else
        {
            //没有登录  打开登录界面
            GameBus.getInstance().addEventListener( LoginEvent.Login, this.login, this );
            Login.getInstance().login();
        }
    }
    
    /**登录游戏**/
    private login( event: LoginEvent ): void
    {
        GameBus.getInstance().removeEventListener( LoginEvent.Login, this.login, this );
        this.loginView.dispose();
        this.stage.removeChild( this.loginView );
        this.createGameScene();
    }
}


